package org.itboys.mobile.service.mysql.web.product;

import org.apache.commons.lang3.StringUtils;
import org.itboys.admin.dto.lasted.SundayUploadDto;
import org.itboys.admin.entity.lasted.SystemDictionary;
import org.itboys.admin.service.lasted.SundayUploadService;
import org.itboys.admin.service.lasted.SystemDictionaryService;
import org.itboys.commons.ErrorException;
import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.mobile.entity.mysql.product.SundayProductRecord;
import org.itboys.mobile.service.mongo.web.SundayPermissionService;
import org.itboys.mobile.service.mongo.web.SundayRecordPermissionService;
import org.itboys.mysql.service.BaseMySqlService;
import org.itboys.param.PageResult;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：zzq
 * 时间：2017/10/25
 * 描述：雄安加盟网_项目记录
 */
@Service
public class SundayProductRecordService extends BaseMySqlService<SundayProductRecord>{

    @Autowired
    private SundayUploadService uploadService;
    @Autowired
    private SundayRecordPermissionService recordPermissionService;
    @Autowired
    private SystemDictionaryService dictionaryService;
    /**
     * 分页查询商品记录
     *
     * @param request
     * @return
     */
    public PageResult<SundayProductRecord> selectProduct(HttpServletRequest request, List<Long> ids) {
        Map<String, Object> param = ParamUtil.packageMysqlPageParam(request, "name", "number", "categoryId", "categoryName","type","status");
        if (ListUtil.isNotNull(ids)) {
            param.put("ids", ids);
        }
        //2017年8月11日新增，如果传入了用户ID。则从权限中的获取对应的商品权限
        String memberId=request.getParameter("memberId");
        if(StringUtils.isNotEmpty(memberId)){
            List<Long> otherIds = recordPermissionService.getRecordPermission(Long.valueOf(memberId),1);
            if (ListUtil.isNull(otherIds)) {
                otherIds.add(0l);
            }
            param.put("ids", otherIds);
        }


        return new PageResult<SundayProductRecord>(super.select(param), super.count(param));
    }
    /**
     * 新增/修改商品
     * @param product
     * @param imageFile
     * @param rollImageFiles

     * @throws IOException
     */
    @Transactional
    public void save(
            SundayProductRecord product,
            MultipartFile imageFile,
            MultipartFile[] rollImageFiles,
            Long memberId
    ) throws  Exception {
        //保存主图
        Map<String, String> map = uploadService.uploadSingle(imageFile);
        if(StringUtils.isNotEmpty(map.get(uploadService.UPLOAD_HALF_PATH))){
            product.setImage(map.get(uploadService.UPLOAD_HALF_PATH));
        }

        //编辑
        if(LongUtil.isNotZreo(product.getId())){
            //product.setUpdater(creator);
            //校验编号
            if(StringUtils.isNotEmpty(product.getNumber())){
                Map<String, Object> param = new HashMap<String, Object>();
                param.put("id",product.getId());
                param.put("number_equal", product.getNumber());
                //param.put("type", Finals.TYPE_TIANJIE);
                //param.put("isDeletedNotEqual", Finals.YES);
                if(ListUtil.isNotNull(super.select(param))){
                    throw new ErrorException("商品编号不能重复");
                }
            }
            super.update(product);
        }else{
            //校验编号
            Map<String, Object> param = new HashMap<String, Object>();
            if(StringUtils.isNotEmpty(product.getNumber())){
                param.put("number_equal", product.getNumber());
                if(ListUtil.isNotNull(super.select(param))){
                    throw new ErrorException("商品编号不能重复");
                }
            }

            //product.setIsDeleted(Finals.NO);
            //product.setType(Finals.TYPE_TIANJIE);
            //product.setZoneId(zoneId);
            super.insert(product);
            //2017年8月13日，如果新增的是商户商品，需要添加对应的权限
            if(LongUtil.isNotZreo(memberId)){
                recordPermissionService.saveRecordPermission(memberId,null,product.getId(),1,false);
            }
        }
        //保存轮播图
        List<Map<String, String>> maps = uploadService.
                uploadMultiWithRecord(rollImageFiles,product.getId(),SundayProductRecord.class.getSimpleName(),"商品ID"+product.getId()+",的轮播图");

    }


    /**
     * 查询商品详情。后台
     * @param productId
     * @return
     */
    public SundayProductRecord findOne(Long productId){
        SundayProductRecord product=null;
        if(LongUtil.isNotZreo(productId)){
            product = super.find(productId);
            //TianJieProduct
            //轮播图
            Map<String,Object> imgParam = new HashMap<String, Object>();
            imgParam.put("outClassName", product.getClass().getSimpleName().toString());
            imgParam.put("outClassId", productId);
            List<SundayUploadDto> rollImages = uploadService.selectNoPage(product.getId(),SundayProductRecord.class.getSimpleName());
            product.setRollImages(rollImages);

        }else{
            product=new SundayProductRecord();
        }

        return product;
    }

    /**
     * 组装标签
     */
    public SundayProductRecord packageTags(SundayProductRecord product,  boolean isAll){

        //组装项目招商模式标签
        List<SystemDictionary> joinModelDictionaries=dictionaryService.getDictionaryByKey("join_model");
        if(product.getJoinModel()==null)product.setJoinModel("");
        String [] joinModelTagIds = product.getJoinModel().split(",");

        List<Map<String,Object>> joinModelTags = new ArrayList<Map<String, Object>>();
        for(SystemDictionary dictionary:joinModelDictionaries){
            Map<String,Object> tag=new HashMap<String,Object>();
            tag.put("id",dictionary.getId());
            tag.put("name",dictionary.getValue());
            int isChecked=0;

            for(String modelTagId:joinModelTagIds){
                if(modelTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
                    isChecked=1;
                    break;
                }
            }
            tag.put("isChecked",isChecked);
            if(!isAll){
                if(isChecked==1)joinModelTags.add(tag);
            }else{
                joinModelTags.add(tag);
            }

        }
        product.setJoinModelTags(joinModelTags);

        //组装项目经营模式标签
        List<SystemDictionary> managerModelDictionaries=dictionaryService.getDictionaryByKey("manager_model");
        if(product.getManagerModel()==null)product.setManagerModel("");
        String [] managerModelTagIds = product.getManagerModel().split(",");

        List<Map<String,Object>> managerModelTags = new ArrayList<Map<String, Object>>();
        for(SystemDictionary dictionary:managerModelDictionaries){
            Map<String,Object> tag=new HashMap<String,Object>();
            tag.put("id",dictionary.getId());
            tag.put("name",dictionary.getValue());
            int isChecked=0;

            for(String managerTagId:managerModelTagIds){
                if(managerTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
                    isChecked=1;
                    break;
                }
            }
            tag.put("isChecked",isChecked);
            if(!isAll){
                if(isChecked==1)managerModelTags.add(tag);
            }else{
                managerModelTags.add(tag);
            }
        }
        product.setManagerModelTags(managerModelTags);


        //组装项目适合人群标签
        List<SystemDictionary> fitPersonDictionaries=dictionaryService.getDictionaryByKey("fit_person");
        if(product.getFitPerson()==null)product.setFitPerson("");
        String [] fitPersonTagIds = product.getFitPerson().split(",");

        List<Map<String,Object>> fitPersonTags = new ArrayList<Map<String, Object>>();
        for(SystemDictionary dictionary:fitPersonDictionaries){
            Map<String,Object> tag=new HashMap<String,Object>();
            tag.put("id",dictionary.getId());
            tag.put("name",dictionary.getValue());
            int isChecked=0;

            for(String fitPersonTagId:fitPersonTagIds){
                if(fitPersonTagId.equalsIgnoreCase(String.valueOf(dictionary.getId()))){
                    isChecked=1;
                    break;
                }
            }
            tag.put("isChecked",isChecked);
            if(!isAll){
                if(isChecked==1)managerModelTags.add(tag);
            }else{
                fitPersonTags.add(tag);
            }
        }
        product.setFitPersonTags(fitPersonTags);

        return product;
    }
}
